import axios from 'axios';
import type { ApiInfo } from '../model';

/**
 * API服务类
 * 提供API详情获取等功能
 */
export class ApiService {
  /**
   * 获取API详情
   * @param apiId API ID
   * @returns API详情数据
   */
  static async getApiDetail(apiId: string): Promise<ApiInfo> {
    try {
      const response = await axios.get<ApiInfo>(`/docs/api/${apiId}`);
      return response.data;
    } catch (error) {
      console.error('获取API详情失败:', error);
      throw new Error('获取API详情失败');
    }
  }

  /**
   * 测试API调用
   * @param api API信息
   * @param params 请求参数
   * @returns 测试结果
   */
  static async testApiCall(api: ApiInfo, params: any) {
    try {
      const method = api.method.toUpperCase();
      const url = `http://localhost:8080${api.path}`;
      
      // 构建请求配置
      const config: any = {
        method,
        url,
        headers: {
          'Content-Type': 'application/json',
          ...api.headers?.reduce((acc: any, header: any) => {
            if (header.name && header.value) {
              acc[header.name] = header.value;
            }
            return acc;
          }, {})
        }
      };
      
      // 根据请求方法设置参数
      if (['POST', 'PUT', 'PATCH'].includes(method)) {
        config.data = params;
      } else {
        config.params = params;
      }
      
      const response = await axios(config);
      return response.data;
    } catch (error) {
      console.error('API测试失败:', error);
      throw error;
    }
  }
}